package org.hako.recite.word.tool;

import java.util.Arrays;

/**
 * Detect yomi of two kannjis.
 * 
 * @since 0.4.14
 * @author <a href="mailto:xnnyygn@gmail.com">xnnyygn</a>
 */
public class DoubleKannjiDetector implements KannjiYomiDetector {

	@Override
	public boolean check(String rawKannji, String rawYomi,
			KannjiExtractResult extractResult) {
		return extractResult.getCount() == 2;
	}

	@Override
	public KannjiYomiDetectResult detect(String rawKannji, String rawYomi,
			KannjiExtractResult extractResult) {
		int firstKannjiIndex = extractResult.get(0);
		int secondKannjiIndex = extractResult.get(1);
		if (secondKannjiIndex - firstKannjiIndex == 1) {
			return new KannjiYomiDetectResult(
					KannjiYomiDetectResult.ERROR_CODE_FAILURE);
		}
		String midYomi = rawKannji.substring(firstKannjiIndex + 1,
				secondKannjiIndex);
		int midYomiIndex = rawYomi.indexOf(midYomi, firstKannjiIndex);
		if (rawYomi.indexOf(midYomi, midYomiIndex + 1) >= 0) {
			return new KannjiYomiDetectResult(
					KannjiYomiDetectResult.ERROR_CODE_FAILURE);
		}

		// get first pair
		String kannji = rawKannji.substring(firstKannjiIndex,
				firstKannjiIndex + 1);
		String yomi = rawYomi.substring(firstKannjiIndex, midYomiIndex);
		KannjiYomiPair firstPair = new KannjiYomiPair(kannji, yomi);

		// get second pair
		kannji = rawKannji.substring(secondKannjiIndex, secondKannjiIndex + 1);
		yomi = rawYomi.substring(midYomiIndex + secondKannjiIndex
				- firstKannjiIndex - 1, rawYomi.length()
				- (rawKannji.length() - secondKannjiIndex - 1));
		KannjiYomiPair secondPair = new KannjiYomiPair(kannji, yomi);
		return new KannjiYomiDetectResult(Arrays.asList(firstPair, secondPair),
				generateKannjiWithYomi(rawKannji, firstKannjiIndex,
						secondKannjiIndex, firstPair, secondPair));
	}

	/**
	 * Generate kannji with yomi.
	 * 
	 * @param rawKannji
	 * @param firstKannjiIndex
	 * @param secondKannjiIndex
	 * @param firstPair
	 * @param secondPair
	 * @return
	 */
	private String generateKannjiWithYomi(String rawKannji,
			int firstKannjiIndex, int secondKannjiIndex,
			KannjiYomiPair firstPair, KannjiYomiPair secondPair) {
		StringBuilder kannjiWithYomiBuilder = new StringBuilder();
		kannjiWithYomiBuilder.append(rawKannji.substring(0,
				firstKannjiIndex + 1));
		kannjiWithYomiBuilder.append('(');
		kannjiWithYomiBuilder.append(firstPair.getYomi());
		kannjiWithYomiBuilder.append(')');
		kannjiWithYomiBuilder.append(rawKannji.substring(firstKannjiIndex + 1,
				secondKannjiIndex + 1));
		kannjiWithYomiBuilder.append('(');
		kannjiWithYomiBuilder.append(secondPair.getYomi());
		kannjiWithYomiBuilder.append(')');
		kannjiWithYomiBuilder
				.append(rawKannji.substring(secondKannjiIndex + 1));
		return kannjiWithYomiBuilder.toString();
	}

}
